//
//  CZEmotionPackage.swift
//  刷新控件
//
//  Created by Albert Zhu on 16/10/25.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit
import YYModel


/// 某一个种类的表情包
class CZEmotionPackage: NSObject {

    /// 表情包目录
    // 目录设置后，通过目录在bundle中找到存放表情模型相关数据的数组，并添加到表情模型数组中
    var id: String? {
        didSet {
            guard let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil),
                let bundle = Bundle(path: path),
                let emoPath = bundle.path(forResource: "info.plist", ofType: nil, inDirectory: id),
                let dic = NSDictionary(contentsOfFile: emoPath) as? [String:Any],
                let array = dic["emoticons"] as? [[String:String]]
                else {return}
            
            emotions = NSArray.yy_modelArray(with: CZEmotionModel.self, json: array) as? [CZEmotionModel] ?? []
            
            for model in emotions {
                model.id = id
            }
        }
    }
    
    /// 懒加载模型空数组
    lazy var emotions = [CZEmotionModel]()
    
    /// 表情页面数量
    var numberOfPages: Int {
        return (emotions.count - 1) / 20 + 1
    }
    
    func emotion(page: Int) -> [CZEmotionModel] {
        
        /// 每页的表情数量
        let count = 20
        /// 某一页的起始位置
        let location = page * 20
        /// 该页的表情数量
        var length = count
        
        // 判断数组是否越界
        if location + length > emotions.count {
            length = emotions.count - location
        }
        
        /// 截取子数组
        let array = (emotions as NSArray).subarray(with: NSRange(location: location, length: length))
        
        return array as! [CZEmotionModel]
    }
    
    override var description: String {
        return yy_modelDescription()
    }
}
